<template>
  <div>
    <Section>
      <div
        class="relative flex flex-col items-center justify-between gap-y-4 pb-10 pt-10 md:flex-row"
      >
        <div class="max-w-md space-y-2 lg:max-w-xl">
          <h2 class="font-sans text-4xl font-medium capitalize">
            标签为
            <span class="text-primary">{{ tag?.object.name }}</span>
            的全部文章
          </h2>
          <p class="font-sans text-sm lg:text-base">
            您的高质量内容的目的地，在我们的大部分文章保持最新、最引人入胜和发人深省的文章！
          </p>
        </div>
        <InnerLinks />
      </div>
      <div
        class="mb-20 grid gap-6 sm:grid-cols-3 sm:gap-4 md:grid-cols-2 lg:grid-cols-3"
        v-if="data?.success"
      >
        <PostCardWithDigest
          v-for="post in data?.query.results"
          :key="post.id"
          :post="post"
          digest
        />
      </div>
      <div class="flex items-center justify-between px-4">
        <InnerLinks />
        <ZPagination
          :total="total"
          v-model:page="page"
          v-model:page-size="pageSize"
          :buttons="['first', 'last']"
        />
      </div>
    </Section>
  </div>
</template>
<script setup lang="ts">
import type { Tag, Post, User } from "@/stores/types";
import { useApiFetch, ApiResponse } from "@/composables/useApiFetch";
import { useUrlParams } from "@/composables/useUrlParams";
import InnerLinks from "@/components/InnerLinks.vue";
import { useRouteParamsWith } from "@/composables/useRouteParamsWith";

const tagId = useRouteParamsWith("id");
const url = computed(() => `/tags/${tagId.value}`);
const { data: tag } = useApiFetch(url, { refetch: true }).json<
  ApiResponse<Tag>
>();

const total = ref(0),
  page = ref(1),
  pageSize = ref(12);
const params = computed(() => ({
  tags: [tagId.value],
  limit: pageSize.value,
  offset: (page.value - 1) * pageSize.value,
}));
const urlParams = useUrlParams(params);
// 获取所有文章
const { data } = useApiFetch(
  computed(() => `/posts?${urlParams.value}`),
  { refetch: true },
).json<ApiResponse<Post & User>>();

watch(data, () => {
  if (data.value?.success) {
    total.value = data.value.query.count;
  }
});
</script>
